package by.averianov.discounta.dataaccess.impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;

import org.hibernate.jpa.criteria.OrderImpl;
import org.springframework.stereotype.Repository;

import by.averianov.discounta.dataaccess.CardTypeDao;
import by.averianov.discounta.datamodel.CardType;
import by.averianov.discounta.datamodel.CardType_;

@Repository
public class CardTypeDaoImpl extends AbstractDaoImpl<Long, CardType> implements CardTypeDao {
	
	protected CardTypeDaoImpl() {
		super(CardType.class);
	}
	
	@Override
	public CardType getCardTypeByName(String name) {
		CriteriaBuilder cb = getEm().getCriteriaBuilder();

		CriteriaQuery<CardType> criteria = cb.createQuery(CardType.class);
        Root<CardType> root = criteria.from(CardType.class);

        criteria.select(root);
        criteria.where(cb.equal(root.get(CardType_.nameCardType), name));

        TypedQuery<CardType> query = getEm().createQuery(criteria);
        CardType results = query.getSingleResult();
        return results;
	}
	
	@Override
	public List<CardType> getAllCardType(SingularAttribute<CardType, ?> attr, boolean ascending, int startRecord, int pageSize) {
		CriteriaBuilder cb = getEm().getCriteriaBuilder();

		CriteriaQuery<CardType> criteria = cb.createQuery(CardType.class);
		Root<CardType> root = criteria.from(CardType.class);

		criteria.select(root);
		criteria.orderBy(new OrderImpl(root.get(attr), ascending));
		TypedQuery<CardType> query = getEm().createQuery(criteria);
		query.setFirstResult(startRecord);
		query.setMaxResults(pageSize);

		List<CardType> results = query.getResultList();
		return results;
	}

	/*@Override
	public List<CardType> getAll() {
		CriteriaBuilder cb = getEm().getCriteriaBuilder();

		CriteriaQuery<CardType> q = cb.createQuery(CardType.class);
		Root<CardType> c = q.from(CardType.class);

		q.select(c);

		TypedQuery<CardType> query = getEm().createQuery(q);
		List<CardType> results = query.getResultList();
		return results;
	}*/

}
